package com.ruoyi.common.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CheckSignUtil {
	
	private static final Logger _log = LoggerFactory.getLogger(CheckSignUtil.class);
	
    public static String formatUrlMap(Map<String, String> paraMap)
    {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try
        {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
            {

                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
                {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds)
            {
                if (StringUtils.isNotBlank(item.getKey()))
                {
                    String key = item.getKey();
                    String val = item.getValue();
                    if(val!=null &&!"".equals(val)) {
                        val = URLEncoder.encode(val, "utf-8").toLowerCase();
                        buf.append(key + "=" + val);
                        buf.append("&");
                    }else {
                        buf.append(key + "=");
                        buf.append("&");
                    }

                }
                
            }
            buff = buf.toString();
            if (buff.isEmpty() == false)
            {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        String sign = MD5Util.MD5(buff);
        _log.info("【signStr】{}", buff);
        _log.info("【sign】{}", sign);
        return sign;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //字典序列排序
        Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("total_fee","200");
        paraMap.put("appid", "wxd678efh567hg6787");
        paraMap.put("out_trade_no","20150806125346");
        String url = CheckSignUtil.formatUrlMap(paraMap);
        //System.out.println(url);
    }
}